package com.definity.toolkit.i18n;

import java.net.MalformedURLException;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

public final class I18n {

	private final I18n parent;
	private final String baseName;
	private final ClassLoader classLoader;
	
	private ResourceBundle bundle;

	I18n(String baseName) {
		this(null, null, baseName);
	}

	I18n(ClassLoader classLoader, String baseName) {
		this(classLoader, null, baseName);
	}
	
	I18n(I18n parent, String baseName) {
		this(null, parent, baseName);
	}
	
	I18n(ClassLoader classLoader, I18n parent, String baseName) {
		this.parent = parent;
		this.baseName = baseName;
		
		if (classLoader == null) {
			classLoader = getClass().getClassLoader();
		}
		this.classLoader = classLoader;
	}
	
	String getName() {
		return baseName;
	}
	
	synchronized void load(Locale locale) throws MalformedURLException {
		if (bundle == null) {
			bundle = ResourceBundle.getBundle("i18n/" + baseName, locale, classLoader);
		}
	}
	
	public String tl(String key) {
		if (key == null) {
			return null;
		}
		
		String msg;
		try {
			msg = bundle.getString(key);
		} catch (MissingResourceException e) {
			if (parent != null) {
				msg = parent.tl(key);
			} else {
				msg = "?" + key + "?";
			}
		}
		return msg;
	}
	
	public String tl(String key, Object... args) {
		return String.format(tl(key), args);
	}
	
}
